import AsyncStorage from '@/utils/AsyncStorage';

const passwordStorageKey = 'PasswordStorageKey';

let passwordInfoMap: any;

async function loadPasswordStorage() {
  const str = await AsyncStorage.getItem(passwordStorageKey);
  if (str) {
    try {
      passwordInfoMap = JSON.parse(str);
      return;
    } catch (err) {
      console.log('loadPasswordStorage error', err);
    }
  } else {
    passwordInfoMap = {};
  }
}

export async function getDevicePassword(device: IDevice) {
  if (!passwordInfoMap) {
    await loadPasswordStorage();
  }
  if (!passwordInfoMap) {
    return undefined;
  }
  return passwordInfoMap[device.deviceId];
}

export async function saveDevicePassword({ device, password }: { device: IDevice, password: string }) {
  if (device && password && password.length > 0) {
    if (!passwordInfoMap) {
      await loadPasswordStorage();
    }
    if (!passwordInfoMap) {
      return { success: false };
    }
    passwordInfoMap[device.deviceId] = password;
    try {
      const str = JSON.stringify(passwordInfoMap);
      if (str) {
        await AsyncStorage.setItem(passwordStorageKey, str);
        return { success: true };
      }
    } catch (err) {
      console.log('saveDevicePassword error', err);
    }
  }
  return { success: false };
}

export function clearAllPassword() {
  AsyncStorage.removeItem(passwordStorageKey);
}
